package com.ruoyi.web.controller.system;

import java.util.List;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.TUser;
import com.ruoyi.system.domain.TUserStatus;
import com.ruoyi.system.domain.vo.TUserVo;
import com.ruoyi.system.service.ITUserService;
import com.ruoyi.system.service.ITUserStatusService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * APP用户Controller
 * 
 * @author ruoyi
 * @date 2025-08-18
 */
@RestController
@RequestMapping("/system/tuser")
@Api("APP用户")
public class TUserController extends BaseController
{
    @Autowired
    private ITUserService tUserService;

    @Autowired
    private ITUserStatusService tUserStatusService;

    /**
     * 查询用户列表
     */
    @ApiOperation(value = "用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(TUser tUser)
    {
        // 手动分页以确保count查询准确性
        startPage();
        if (tUser.getDeleted() == null){
            tUser.setDeleted(0L);
        }
        List<TUserVo> list = tUserService.selectTUserVoList(tUser);
        
        // 获取准确的总数
        int total = tUserService.countTUserList(tUser);
        
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(200);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(total);
        
        return rspData;
    }

    /**
     * 导出APP用户列表
     */
    @ApiOperation(value = "导出APP用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @Log(title = "APP用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TUser tUser)
    {
        List<TUser> list = tUserService.selectTUserList(tUser);
        ExcelUtil<TUser> util = new ExcelUtil<TUser>(TUser.class);
        util.exportExcel(response, list, "APP用户数据");
    }

    /**
     * 获取APP用户详细信息
     */
    @ApiOperation(value = "获取APP用户详细信息")
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(tUserService.selectTUserById(id));
    }

    /**
     * 新增APP用户
     */
    @ApiOperation(value = "新增APP用户")
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "APP用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TUser tUser) throws Exception {
        return toAjax(tUserService.insertTUser(tUser));
    }

    /**
     * 修改APP用户
     */
    @ApiOperation(value = "修改APP用户")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "APP用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TUser tUser)
    {
        return toAjax(tUserService.updateTUser(tUser));
    }

    /**
     * 删除APP用户
     */
    @ApiOperation(value = "删除APP用户")
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "APP用户", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(tUserService.deleteTUserByIds(ids));
    }

    /**
     * 获取用户状态
     */
    @ApiOperation(value = "获取用户状态")
    @GetMapping("/status/{uid}")
    public AjaxResult getUserStatus(@PathVariable("uid") String uid)
    {
        TUserStatus userStatus = tUserStatusService.selectTUserStatusByUid(uid);
        if (userStatus == null) {
            // 如果没有状态记录，默认为正常状态
            userStatus = new TUserStatus();
            userStatus.setUid(uid);
            userStatus.setStatus(0); // 0 正常
            userStatus.setDt(System.currentTimeMillis());
        }
        return success(userStatus);
    }

    /**
     * 设置用户状态
     */
    @ApiOperation(value = "设置用户状态")
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "设置用户状态", businessType = BusinessType.UPDATE)
    @PostMapping("/status")
    public AjaxResult setUserStatus(@RequestBody TUserStatus userStatus)
    {
        return toAjax(tUserStatusService.setUserStatus(userStatus.getUid(), userStatus.getStatus()));
    }


    /**
     * 查询禁用用户列表（状态为禁言或封禁的用户）
     */
    @ApiOperation(value = "查询禁用用户列表")
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/disabled")
    public TableDataInfo listDisabledUsers(TUser tUser)
    {
        tUser.setDisabled(1);
        return list(tUser);
    }
}
